package com.toro.server.handler;

import com.toro.message.GroupChatRequestMessage;
import com.toro.message.GroupChatResponseMessage;
import com.toro.dao.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @ClassName: GroupChatRequestMessageHandler
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/12 19:10
 */
@Slf4j
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        log.info("发送群消息请求：{}", msg);
        String from = msg.getFrom();
        String content = msg.getContent();
        String groupName = msg.getGroupName();
        GroupChatResponseMessage groupChatResponseMessage = null;

        List<Channel> channels = GroupSessionFactory.getGroupSession()
                .getMembersChannel(msg.getGroupName());
        log.info("获取到的在线用户Channel：{}", channels);

        for (Channel channel : channels) {
            groupChatResponseMessage = new GroupChatResponseMessage(groupName, from, content);
            groupChatResponseMessage.setSuccess(true);
            channel.writeAndFlush(groupChatResponseMessage);
            log.info("给用户发送的消息：{}", groupChatResponseMessage);
        }
    }
}
